package cn.myframe.service.sys.impl;

import cn.myframe.dao.sys.SysRoleCompanyDao;
import cn.myframe.dao.sys.SysRoleDao;
import cn.myframe.dao.sys.SysRoleMenuDao;
import cn.myframe.entity.sys.SysRoleCompanyEntity;
import cn.myframe.entity.sys.SysRoleEntity;
import cn.myframe.entity.sys.SysRoleMenuEntity;
import cn.myframe.service.BaseServiceImpl;
import cn.myframe.service.sys.SysRoleService;
import cn.myframe.shiro.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;


@Service("sysRoleService")
public class SysRoleServiceImpl extends BaseServiceImpl<SysRoleDao,SysRoleEntity> implements SysRoleService {

    @Autowired
    private SysRoleMenuDao sysRoleMenuDao;
    @Autowired
    private SysRoleCompanyDao sysRoleCompanyDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateWithPerms(SysRoleEntity sysRole) {
        baseMapper.updateById(sysRole);
        sysRoleMenuDao.deleteByRoleId(sysRole.getRoleId());
        sysRoleCompanyDao.deleteByRoleId(sysRole.getRoleId());
        insertRoleMenu(sysRole);
        insertRoleCompany(sysRole);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertWithPerms(SysRoleEntity sysRole) {
        sysRole.setCreateTime(new Date());
        sysRole.setCreateBy(ShiroUtils.getUserEntity().getUserId());
        baseMapper.insert(sysRole);
        insertRoleMenu(sysRole);
        insertRoleCompany(sysRole);
    }

    private void insertRoleCompany(SysRoleEntity sysRole) {
        for (Long companyNo : sysRole.getCompanyNoList()) {
            SysRoleCompanyEntity sysRoleCompanyEntity = new SysRoleCompanyEntity();
            sysRoleCompanyEntity.setRoleId(sysRole.getRoleId());
            sysRoleCompanyEntity.setCompanyNo(companyNo);
            sysRoleCompanyDao.insert(sysRoleCompanyEntity);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteWithPerms(Long[] ids) {
        baseMapper.deleteBatchIds(Arrays.asList(ids));
        for (Long id : ids) {
            sysRoleMenuDao.deleteByRoleId(id);
            sysRoleCompanyDao.deleteByRoleId(id);
        }
    }

    @Override
    public Boolean hasPerm(Long roleId, String perm) {
        return baseMapper.hasPerm(roleId, perm) > 0;
    }

    private void insertRoleMenu(SysRoleEntity sysRole) {
        for (Long menuId : sysRole.getMenuIdList()) {
            SysRoleMenuEntity sysRoleMenuEntity = new SysRoleMenuEntity();
            sysRoleMenuEntity.setRoleId(sysRole.getRoleId());
            sysRoleMenuEntity.setMenuId(menuId);
            sysRoleMenuDao.insert(sysRoleMenuEntity);
        }
    }
}
